import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/utils/log.dart';

class MyInAppBrowser extends InAppBrowser {
  CookieManager cookieManager = CookieManager.instance();
  final box = Hive.box('appconfig');
  final expiresDate =
      DateTime.now().add(Duration(days: 3)).millisecondsSinceEpoch;

  void loadautoken() async {
    await cookieManager.setCookie(
      url: WebUri(Constants.BaseURL),
      name: "nanhaiV4.8Role",
      value: box.get(CacheManagerKey['nanhairole'].toString()) ?? '',
      domain: Constants.BaseDomain,
      path: '/',
      expiresDate: expiresDate,
      isSecure: true,
    );

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student) {
      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8StudentSession",
        value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );

      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8StudentUserId",
        value: box.get(CacheManagerKey['username'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );
    }

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Individual) {
      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8IndividualSession",
        value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );

      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8IndividualUserId",
        value: box.get(CacheManagerKey['username'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );
    }

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_SchoolAdmin) {
      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8SchooladminSession",
        value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );

      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8SchooladminUserId",
        value: box.get(CacheManagerKey['username'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );
    }

    if (box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher) {
      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8TeacherSession",
        value: box.get(CacheManagerKey['authtoken'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );

      await cookieManager.setCookie(
        url: WebUri(Constants.BaseURL),
        name: "nanhaiV4.8TeacherUserId",
        value: box.get(CacheManagerKey['username'].toString()) ?? '',
        domain: Constants.BaseDomain,
        path: '/',
        expiresDate: expiresDate,
        isSecure: true,
      );
    }
  }

  @override
  Future onBrowserCreated() async {
    Log.debug("My inapp browser created!");

    var settings = InAppBrowserClassSettings(
        browserSettings: InAppBrowserSettings(
            allowGoBackWithBackButton: false, hideUrlBar: true),
        webViewSettings: InAppWebViewSettings(
            useShouldOverrideUrlLoading: true,
            mediaPlaybackRequiresUserGesture: false,
            useHybridComposition: true,
            allowsInlineMediaPlayback: true,
            allowFileAccessFromFileURLs: true,
            allowUniversalAccessFromFileURLs: true,
            cacheEnabled: true,
            domStorageEnabled: true,
            javaScriptEnabled: true,
            allowsPictureInPictureMediaPlayback: true,
            enableViewportScale: true,
            disableLongPressContextMenuOnLinks: true,
            //requestedWithHeaderMode: RequestedWithHeaderMode.NO_HEADER,
            //iframeAllow: "camera; microphone",
            //iframeAllowFullscreen: true,
            mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW));

    loadautoken();
    setSettings(settings: settings);
  }

  @override
  Future onLoadStart(url) async {
    //print("Started $url");
  }

  @override
  Future onLoadStop(url) async {
    //print("Stopped $url");
  }

  @override
  void onReceivedError(WebResourceRequest request, WebResourceError error) {
    //print("Can't load ${request.url}.. Error: ${error.description}");
  }

  @override
  void onProgressChanged(progress) {
    //print("Progress: $progress");
  }

  @override
  void onExit() {
    //print("Browser closed!");
  }
}
